#include "oled_ui.h"
#include "Components/basic.h"
#include "Components/oled_hardware_i2c.h"
#include <stdint.h>
#include <string.h>

#define TAG "OLED_UI"

// 全局变量
ui_menu_state_t currentState = MAIN_MENU;
uint8_t currentSelection = 0;
uint8_t subMenuSelection = 0;
uint8_t settingsParamIndex = 0;

char *mainTitle = "EDC Car 1.0";

// 菜单项定义
#define MAX_ITEMS 5
#define MENU_ITEM_LENGTH 20
char menuItems[MAX_ITEMS][MENU_ITEM_LENGTH] = {
    "1.TRACK", "2.FIXED L", "3.FREE L", "4.T & L", "5.T & L O"};

// 参数存储
extern uint8_t target_circles;
extern uint16_t user_target_angle;

// 模式状态 (0=停止, 1=运行)
uint8_t modeStatus[MAX_ITEMS] = {0};

// 回调函数指针
mode_action_callback_t startCallbacks[MAX_ITEMS] = {NULL};
mode_action_callback_t stopCallbacks[MAX_ITEMS] = {NULL};

// API函数 --------------------------------------------------

// // 设置目标圈数
// void uiSetTargetCircles(uint8_t circles)
// {
//   target_circles = (circles > 99) ? 99 : circles;
// }

// // 获取目标圈数
// uint8_t uiGetTargetCircles(void) { return target_circles; }

// // 设置目标角度
// void uiSetTargetAngle(uint16_t angle)
// {
//   user_target_angle = (angle > 360) ? 360 : angle;
// }

// // 获取目标角度
// uint16_t uiGetTargetAngle(void) { return user_target_angle; }

// 注册启动回调函数
void uiRegisterStartCallback(uint8_t index, mode_action_callback_t callback)
{
  if (index < MAX_ITEMS)
  {
    startCallbacks[index] = callback;
  }
}

// 注册停止回调函数
void uiRegisterStopCallback(uint8_t index, mode_action_callback_t callback)
{
  if (index < MAX_ITEMS)
  {
    stopCallbacks[index] = callback;
  }
}

// 设置模式状态
void uiSetModeStatus(uint8_t index, uint8_t status)
{
  if (index < MAX_ITEMS)
  {
    modeStatus[index] = status ? 1 : 0;
  }
}

// 内部函数 --------------------------------------------------

// 获取带状态的菜单项文本
static void getMenuItemText(uint8_t index, char *buffer)
{
  if (index < MAX_ITEMS)
  {
    if (modeStatus[index])
    {
      snprintf(buffer, MENU_ITEM_LENGTH, "%s [RUN]", menuItems[index]);
    }
    else
    {
      snprintf(buffer, MENU_ITEM_LENGTH, "%s [STOP]", menuItems[index]);
    }
  }
}

// 绘制主菜单界面
static void drawMainMenu()
{
  OLED_Clear();

  // 显示大标题
  uint8_t titleX = (SCREEN_WIDTH - strlen(mainTitle) * 8) / 2;
  if (titleX < 0)
    titleX = 0;
  OLED_ShowString(titleX, 0, mainTitle, FONT_SIZE_LARGE);

  // 绘制分隔线
  for (uint8_t i = 0; i < SCREEN_WIDTH; i++)
  {
    OLED_Set_Pos(i, 2);
    OLED_WR_Byte(0xFF, 1);
  }

  // 显示菜单项
  for (uint8_t i = 0; i < MAX_ITEMS; i++)
  {
    uint8_t yPos = 3 + i;
    char itemText[MENU_ITEM_LENGTH];
    getMenuItemText(i, itemText);

    if (i == currentSelection)
    {
      char prefixed[MENU_ITEM_LENGTH + 2];
      snprintf(prefixed, sizeof(prefixed), ">%s", itemText);
      OLED_ShowString(0, yPos, prefixed, FONT_SIZE_SMALL);
    }
    else
    {
      OLED_ShowString(8, yPos, itemText, FONT_SIZE_SMALL);
    }
  }
}

// 绘制子菜单界面
static void drawSubMenu(uint8_t itemIndex)
{
  OLED_Clear();

  // 显示子菜单标题
  char subTitle[32];
  snprintf(subTitle, sizeof(subTitle), "%s Settings", menuItems[itemIndex] + 2);
  OLED_ShowString(0, 0, subTitle, FONT_SIZE_LARGE);

  // 绘制分隔线
  for (uint8_t i = 0; i < SCREEN_WIDTH; i++)
  {
    OLED_Set_Pos(i, 2);
    OLED_WR_Byte(0xFF, 1);
  }

  // 根据模式显示不同选项
  char *options[3];
  switch (itemIndex)
  {
  case 0: // TRACK
    options[0] = "Set target N";
    options[1] = modeStatus[itemIndex] ? "Stop" : "Start";
    options[2] = "Exit";
    break;

  case 1: // FIXED L (只有Start/Stop)
    options[0] = modeStatus[itemIndex] ? "Stop" : "Start";
    options[1] = "Exit";
    options[2] = ""; // 空项
    break;

  case 2: // FREE L
    options[0] = "Set Angle";
    options[1] = modeStatus[itemIndex] ? "Stop" : "Start";
    options[2] = "Exit";
    break;

  default: // 其他模式
    options[0] = modeStatus[itemIndex] ? "Stop" : "Start";
    options[1] = "Configure";
    options[2] = "Exit";
    break;
  }

  for (uint8_t i = 0; i < 3; i++)
  {
    if (options[i][0] == '\0')
      continue; // 跳过空项

    uint8_t yPos = 3 + i;
    if (i == subMenuSelection)
    {
      char prefixed[32];
      snprintf(prefixed, sizeof(prefixed), ">%s", options[i]);
      OLED_ShowString(0, yPos, prefixed, FONT_SIZE_SMALL);
    }
    else
    {
      OLED_ShowString(8, yPos, options[i], FONT_SIZE_SMALL);
    }
  }
}

// 绘制参数设置界面
static void drawSettingsMenu()
{
  OLED_Clear();

  // 显示设置标题
  char title[32];
  if (settingsParamIndex == 0)
  {
    snprintf(title, sizeof(title), "Set Target N");
  }
  else
  {
    snprintf(title, sizeof(title), "Set Angle");
  }
  OLED_ShowString(0, 0, title, FONT_SIZE_LARGE);

  // 绘制分隔线
  for (uint8_t i = 0; i < SCREEN_WIDTH; i++)
  {
    OLED_Set_Pos(i, 2);
    OLED_WR_Byte(0xFF, 1);
  }

  // 显示当前值
  if (settingsParamIndex == 0)
  {
    OLED_ShowString(0, 3, "Current N:", FONT_SIZE_SMALL);
    char numStr[16];
    snprintf(numStr, sizeof(numStr), "%d", target_circles);
    OLED_ShowString(0, 4, numStr, FONT_SIZE_LARGE);
  }
  else
  {
    OLED_ShowString(0, 3, "Current Angle:", FONT_SIZE_SMALL);
    char numStr[16];
    snprintf(numStr, sizeof(numStr), "%d", user_target_angle);
    OLED_ShowString(0, 4, numStr, FONT_SIZE_LARGE);
  }

  // 显示操作提示
  OLED_ShowString(0, 6, "UP/DN:Adjust", FONT_SIZE_SMALL);
  OLED_ShowString(0, 7, "ENT:Save  BCK:Cancel", FONT_SIZE_SMALL);
}

// 界面主函数
void uiInterfaceUpdate()
{
  switch (currentState)
  {
  case MAIN_MENU:
    drawMainMenu();
    break;
  case SUB_MENU:
    drawSubMenu(currentSelection);
    break;
  case SETTINGS_MENU:
    drawSettingsMenu();
    break;
  }
}

// 按键处理函数
void uiHandleInput(ui_key_code_t key)
{
  switch ((int)key)
  {
  case KEY_UP:
    if (currentState == MAIN_MENU)
    {
      currentSelection =
          (currentSelection == 0) ? MAX_ITEMS - 1 : currentSelection - 1;
    }
    else if (currentState == SUB_MENU)
    {
      // 根据当前模式确定最大选项索引
      uint8_t maxOption = (currentSelection == 1) ? 1 : 2; // FIXED L只有2个选项
      subMenuSelection =
          (subMenuSelection == 0) ? maxOption : subMenuSelection - 1;
    }
    else if (currentState == SETTINGS_MENU)
    {
      // 增加参数值
      if (settingsParamIndex == 0)
      {
        if (target_circles < 99)
          target_circles++;
      }
      else
      {
        if (user_target_angle < 360)
          user_target_angle += 10;
      }
    }
    break;

  case KEY_DOWN:
    if (currentState == MAIN_MENU)
    {
      currentSelection = (currentSelection + 1) % MAX_ITEMS;
    }
    else if (currentState == SUB_MENU)
    {
      // 根据当前模式确定最大选项索引
      uint8_t maxOption = (currentSelection == 1) ? 1 : 2; // FIXED L只有2个选项
      subMenuSelection = (subMenuSelection + 1) % (maxOption + 1);
    }
    else if (currentState == SETTINGS_MENU)
    {
      // 减少参数值
      if (settingsParamIndex == 0)
      {
        if (target_circles > 0)
          target_circles--;
      }
      else
      {
        if (user_target_angle > 0)
          user_target_angle -= 10;
      }
    }
    break;

  case KEY_ENTER:
    if (currentState == MAIN_MENU)
    {
      currentState = SUB_MENU;
      subMenuSelection = 0;
    }
    else if (currentState == SUB_MENU)
    {
      uint8_t modeIndex = currentSelection;

      // 处理子菜单选项
      switch (modeIndex)
      {
      case 0: // TRACK
        if (subMenuSelection == 0)
        {
          settingsParamIndex = 0;
          currentState = SETTINGS_MENU;
        }
        else if (subMenuSelection == 1)
        {
          if (modeStatus[modeIndex])
          {
            if (stopCallbacks[modeIndex])
              stopCallbacks[modeIndex]();
          }
          else
          {
            if (startCallbacks[modeIndex])
              startCallbacks[modeIndex]();
          }
        }
        break;

      case 1: // FIXED L (只有Start/Stop和Exit)
        if (subMenuSelection == 0)
        {
          if (modeStatus[modeIndex])
          {
            if (stopCallbacks[modeIndex])
              stopCallbacks[modeIndex]();
          }
          else
          {
            if (startCallbacks[modeIndex])
              startCallbacks[modeIndex]();
          }
        }
        break;

      case 2: // FREE L
        if (subMenuSelection == 0)
        {
          settingsParamIndex = 1;
          currentState = SETTINGS_MENU;
        }
        else if (subMenuSelection == 1)
        {
          if (modeStatus[modeIndex])
          {
            if (stopCallbacks[modeIndex])
              stopCallbacks[modeIndex]();
          }
          else
          {
            if (startCallbacks[modeIndex])
              startCallbacks[modeIndex]();
          }
        }
        break;

      default: // 其他模式
        if (subMenuSelection == 0)
        {
          if (modeStatus[modeIndex])
          {
            if (stopCallbacks[modeIndex])
              stopCallbacks[modeIndex]();
          }
          else
          {
            if (startCallbacks[modeIndex])
              startCallbacks[modeIndex]();
          }
        }
        break;
      }

      // 如果是退出选项
      if ((currentSelection == 1 && subMenuSelection == 1) ||
          (currentSelection != 1 && subMenuSelection == 2))
      {
        currentState = MAIN_MENU;
      }
    }
    else if (currentState == SETTINGS_MENU)
    {
      currentState = SUB_MENU;
    }
    break;

  case KEY_BACK:
    if (currentState == SUB_MENU)
    {
      currentState = MAIN_MENU;
    }
    else if (currentState == SETTINGS_MENU)
    {
      currentState = SUB_MENU;
    }
    break;
  }
}

// 文字设置函数
void uiSetMainTitle(const char *newTitle) { mainTitle = (char *)newTitle; }

void uiSetMenuItem(uint8_t index, const char *newText)
{
  if (index < MAX_ITEMS)
  {
    strncpy(menuItems[index], newText, MENU_ITEM_LENGTH - 1);
    menuItems[index][MENU_ITEM_LENGTH - 1] = '\0';
  }
}

////////////////////////////Key Section/////////////////////////
#define BUTTON_MIN_WAITE_MS 40
#define BUTTON_MAX_WAITE_MS 300

bool gCheckADC = false;
ui_key_code_t cur_key_code = KEY_NONE;
// const char *key_name[] = {"KEY_UP", "KEY_DOWN", "KEY_ENTER", "KEY_BACK",
//                           "KEY_NONE"};

uint16_t getButtonAdcResult()
{
  uint16_t adcResult = 0;
  gCheckADC = false;

  DL_ADC12_startConversion(BUTTON_ADC_INST);
  while (false == gCheckADC)
  {
    __WFE();
  }

  adcResult = DL_ADC12_getMemResult(BUTTON_ADC_INST, DL_ADC12_MEM_IDX_0);

  gCheckADC = false;
  DL_ADC12_enableConversions(BUTTON_ADC_INST);

  // log(TAG, "adcResult: %d", adcResult);

  return adcResult;
}
ui_key_code_t uiGetKeyCode() { return cur_key_code; }

bool uiShouldCheckKey()
{
  uint16_t adcResult = getButtonAdcResult();

  // log(TAG, "checking adc=%d", adcResult);

#define _in_range(x, min, max) ((x) >= (min) && (x) <= (max))

  cur_key_code = KEY_NONE;
  if (_in_range(adcResult, 1400, 1500))
  {
    cur_key_code = KEY_UP;
  }
  else if (_in_range(adcResult, 2000, 2100))
  {
    cur_key_code = KEY_DOWN;
  }
  else if (_in_range(adcResult, 2400, 2430))
  {
    cur_key_code = KEY_ENTER;
  }
  else if (_in_range(adcResult, 600, 670))
  {
    cur_key_code = KEY_BACK;
  }

  static ui_key_code_t last_key_code = KEY_NONE;
  static uint32_t last_key_ms = 0, need_check_time = 0;

  uint32_t cur_ms = 0;
  mspm0_get_clock_ms(&cur_ms);

  if (cur_ms >= need_check_time && (!(need_check_time & (1 << 31))))
  {
    need_check_time = 0xFFFFFFFF;
    last_key_code = KEY_NONE;
    // log(TAG, "key check time out cur need_check_time: %u", need_check_time);
  }

  if (cur_key_code != last_key_code && cur_key_code != KEY_NONE)
  {
    if (cur_ms - last_key_ms < BUTTON_MIN_WAITE_MS)
    {
      return false;
    }
    else
    {
      last_key_ms = cur_ms;
      last_key_code = cur_key_code;
      need_check_time = cur_ms + BUTTON_MAX_WAITE_MS;

      // log(TAG, "set need_check_time: %d", need_check_time);

      return true;
    }
  }

  return false;
}

void adc_button_init()
{
  NVIC_EnableIRQ(BUTTON_ADC_INST_INT_IRQN);
  /* Confirm VREF has settled before triggering ADC12 conversion */
  while (DL_VREF_CTL1_READY_NOTRDY == DL_VREF_getStatus(VREF))
    ;
  gCheckADC = false;
}

void BUTTON_ADC_INST_IRQHandler(void)
{
  switch (DL_ADC12_getPendingInterrupt(BUTTON_ADC_INST))
  {
  case DL_ADC12_IIDX_MEM0_RESULT_LOADED:
    gCheckADC = true;
    break;
  default:
    break;
  }
}

// 初始化函数
void uiInterfaceInit()
{
  adc_button_init();
  oled_i2c_sda_unlock();
  OLED_Init();
  OLED_ColorTurn(0);
  OLED_DisplayTurn(0);
  OLED_Clear();
  OLED_Display_On();
}
